<template>
  <div class="payment-container">
    <el-card class="payment-card">
      <div slot="header">支付信息</div>
      <el-form :model="form" label-width="100px">
        <el-form-item label="订单总价">
          <span>￥{{ totalPrice }}</span>
        </el-form-item>
        <el-form-item label="配送地址">
          <el-input v-model="form.deliveryAddress" placeholder="请输入配送地址" />
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入订单备注" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">确认支付</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { orderApi } from '@/utils/request'
import { payApi } from '@/utils/request'
export default {
  name: 'Payment',
  data() {
    return {
      totalPrice: this.$route.query.totalPrice || 0,
      form: {
        deliveryAddress: '',
        remark: ''
      }
    }
  },
  methods: {
    async handleSubmit() {
      try {
        const orderId = await orderApi.createOrder({
          itemId: this.$route.query.itemId,
          itemName: this.$route.query.itemName,
          currentPrice: this.$route.query.currentPrice,
          quantity: this.$route.query.quantity,
          totalPrice: this.totalPrice,
          deliveryFee: 0,
          deliveryAddress: this.form.deliveryAddress,
          contactPhone: localStorage.getItem('user-info')?.phone || '',
          remark: this.form.remark
        })
        const response = await payApi.pay({
          subject: `便利购订单-${orderId}`,
          traceNo: orderId,
          totalAmount: this.totalPrice
        })
        // 创建新窗口展示支付宝支付表单
        const newWindow = window.open('', '_blank')
        if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
          throw new Error('支付窗口被浏览器拦截，请允许弹出窗口后再试')
        }
        newWindow.document.write(response.data)
        newWindow.document.close()
        this.$router.push({
          path: '/payment-complete',
          query: { orderId }
        })
      } catch (error) {
        console.error('支付失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.payment-container {
  max-width: 600px;
  margin: 20px auto;
}
.payment-card {
  width: 100%;
}
</style>